from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from neo4j.exceptions import Neo4jError

from config.neo4j_client import get_neo4j_driver


class Command(BaseCommand):
    help = "Inspect KnowledgeNode vertices and REQUIRES edges stored in Neo4j."

    def handle(self, *args, **options):
        if not settings.NEO4J_URI or not settings.NEO4J_PASSWORD:
            raise CommandError("Neo4j 未配置完整 (需要 NEO4J_URI 与 NEO4J_PASSWORD)。")

        driver = get_neo4j_driver()

        try:
            with driver.session() as session:
                node_count = session.run(
                    "MATCH (n:KnowledgeNode) RETURN count(n) AS total"
                ).single()["total"]

                rel_count = session.run(
                    "MATCH (:KnowledgeNode)-[r:REQUIRES]->(:KnowledgeNode) RETURN count(r) AS total"
                ).single()["total"]

                sample_nodes = session.run(
                    """
                    MATCH (n:KnowledgeNode)
                    RETURN n.django_id AS id, n.name AS name, n.mastery_level AS mastery
                    ORDER BY n.django_id ASC
                    LIMIT 5
                    """
                ).data()

                sample_edges = session.run(
                    """
                    MATCH (src:KnowledgeNode)-[:REQUIRES]->(dst:KnowledgeNode)
                    RETURN src.name AS source, dst.name AS target
                    LIMIT 5
                    """
                ).data()
        except Neo4jError as exc:
            raise CommandError(f"Neo4j 查询失败: {exc}") from exc

        self.stdout.write(f"节点总数: {node_count}")
        self.stdout.write(f"依赖关系总数: {rel_count}")

        if sample_nodes:
            self.stdout.write("\n示例节点:")
            for node in sample_nodes:
                self.stdout.write(f"- #{node['id']} {node['name']} (mastery={node['mastery']})")
        else:
            self.stdout.write("\n没有节点可展示。")

        if sample_edges:
            self.stdout.write("\n示例依赖关系:")
            for edge in sample_edges:
                self.stdout.write(f"- {edge['source']} -> {edge['target']}")
        else:
            self.stdout.write("\n没有依赖关系可展示。")
